#pragma once

#include <thread>
#include <memory>

#include "xrtcserver_def.h"
#include "base/lock_queue.h"
#include "rtc_server.h"
#include "stream/rtc_stream_manager.h"

namespace xrtc {
    
class RtcWorker {
public:
    enum {
        QUIT = 0,
        RTC_MSG = 1
    };

    RtcWorker(int worker_id, const RtcServerOptions& options);
    ~RtcWorker();

    int init();
    bool start();
    void stop();
    int notify(int msg);
    void join();
    void pushMsg(std::shared_ptr<RtcMsg> msg);
    bool popMsg(std::shared_ptr<RtcMsg>* msg);
    int sendRtcMsg(std::shared_ptr<RtcMsg> msg);

    friend void rtcWorkerRecvNotify(EventLoop* /*el*/, IOWatcher* /*w*/, int fd, 
        int /*events*/, void* data);

private:
    // 处理不同类型的消息
    void _processNotify(int msg);
    // 解析命令参数
    void _processRtcMsg();
    // 向信令服务器线程返回offer
    void _process_push(std::shared_ptr<RtcMsg> msg);
    // 处理信令服务器发声的answer
    void _process_answer(std::shared_ptr<RtcMsg> msg);

    void _stop();

private:
    RtcServerOptions m_options;
    int m_worker_id;
    std::unique_ptr<std::thread> m_thread;
    EventLoop* m_el;

    IOWatcher* m_pipe_watcher = nullptr;
    int m_notify_recv_fd = -1;
    int m_notify_send_fd = -1;

    ThreadSafeQueue<std::shared_ptr<RtcMsg>> m_msg_queue;

    std::unique_ptr<RtcStreamManager> m_rtc_stream_manager; 
}; 

} // namespaceM xrtc M